<?php


namespace app\controller\admin\system\notice;

use app\common\model\user\User;
use app\common\repositories\system\config\ConfigClassifyRepository;
use app\common\repositories\system\config\ConfigRepository;
use app\common\repositories\system\config\ConfigValueRepository;
use app\validate\admin\SystemAppNoticeConfigValidate;
use crmeb\basic\BaseController;
use crmeb\services\AppTemplateMessageService;
use think\App;
use  app\common\repositories\system\notice\SystemAppNoticeConfigRepository;

class SystemAppNoticeConfig extends BaseController
{
    /**
     * @var CommunityTopicRepository
     */
    protected $repository;

    /**
     * User constructor.
     * @param App $app
     * @param  $repository
     */
    public function __construct(App $app, SystemAppNoticeConfigRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    /**
     * @return mixed
     * @author Qinii
     */
    public function lst()
    {
        $where = $this->request->params(['keyword','type']);
        [$page, $limit] = $this->getPage();
        return app('json')->success($this->repository->getList($where, $page, $limit));
    }


    public function create()
    {
        $data = $this->checkParams();
        $data['const_key'] = trim($data['const_key']);
        if ($this->repository->fieldExists('const_key', $data['const_key'],null))
            return app('json')->fail('通知键名称重复');
        $this->repository->create($data);
        return app('json')->success('添加成功');
    }


    public function update($id)
    {
        $data = $this->checkParams();
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        if ($this->repository->fieldExists('const_key', $data['const_key'],$id))
            return app('json')->fail('通知键名称重复');
        $this->repository->update($id,$data);

        return app('json')->success('编辑成功');
    }


    /**
     * @param $id
     * @return mixed
     * @author Qinii
     */
    public function delete($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $this->repository->delete($id);
        return app('json')->success('删除成功');
    }


    public function checkParams()
    {
        $data = $this->request->params(['notice_title','const_key','notice_info','send_content','type','skip_url','kid']);
        app()->make(SystemAppNoticeConfigValidate::class)->check($data);
        return $data;
    }

    public function getOptions()
    {
        return app('json')->success($this->repository->options());
    }

    public function switchStatus($id)
    {
        $status = $this->request->param('status', 0) == 1 ? 1 : 0;
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');

        $this->repository->swithStatus($id, $status);
        return app('json')->success('修改成功');
    }

    public function detail($id)
    {
        $data = $this->repository->detail($id);
        if(empty($data)) return app('json')->fail('数据不存在');
        return app('json')->success($data);
    }

    public function send($id){
        $res = $this->repository->detail($id);
        if(empty($res)) return app('json')->fail('数据不存在');
        if($res->kid == 0){
            $data=[
                "title"  => $res->notice_title,
                "content"=> $res->notice_info,
                "payload"=>[
                    "url" => $res->skip_url,
                ],
            ];
            $server = app()->make(AppTemplateMessageService::class)->sendAppMsg($data);
        }else{
            $group = explode(',',$res->kid);
            $model = (new User())->where('group_id','in',$group)->whereNotNull('push_clientid');
            $total = $model->count();
            if($total >0){
                $num = ceil($total / 1000) - 1;
                $i = 0;
                while ($i <= $num){
                    $list =  $model->field('push_clientid')->limit($i,1000)->select()->toArray();
                    $server = app()->make(AppTemplateMessageService::class)->sendAppMsg([
                        "title"  => $res->notice_title,
                        "content"=> $res->send_content,
                        "payload"=>[
                            "url" => $res->skip_url,
                        ],
                        "cids"=>array_column($list,'push_clientid'),
                        'requset_id'=>time().rand(10000,99999)
                    ]);
                    $i++;
                }
            }
        }
        $res->send_time = date('Y-m-d H:i:s');
        $res->save();
        return app('json')->success('发送成功');
    }

}
